import classNames from 'classnames';
import React, { Children, useEffect, useState } from 'react';
import { TimelineItemProps } from './timelineItem';

export type TimelinePlacementType = 'up' | 'down'

interface TimelineProps {
    // 是否倒叙
    reverse?: boolean
    // 时间显示的位置
    placement?: TimelinePlacementType
    className?: string
    children?: React.ReactNode
}

const Timeline: React.FC<TimelineProps> = props => {

    const { className, children, reverse, placement } = props;

    const classes = classNames(className, 'yulang-timeline-container');

    // 升序
    const ascendingOrder = (a: TimelineItemProps, b: TimelineItemProps) => {
        return new Date(a.time).getTime() - new Date(b.time).getTime();
    }
    // 降序
    const reverseOrder = (a: TimelineItemProps, b: TimelineItemProps) => {
        return new Date(b.time).getTime() - new Date(a.time).getTime();
    }

    const [childComponent, setChildComponent] = useState<Array<React.FunctionComponentElement<TimelineItemProps>>>([]);

    useEffect(() => {
        const arr: Array<TimelineItemProps & { childElement: React.FunctionComponentElement<TimelineItemProps> }> = [];
        Children.forEach(children, (child) => {
            const childElement = child as React.FunctionComponentElement<TimelineItemProps>
            if (childElement.type.displayName === "TimelineItem") {
                arr.push({
                    ...childElement.props,
                    childElement: React.cloneElement(childElement, { placement: placement ?? 'up' })
                });
            }
        })
        setChildComponent(arr.sort(reverse ? reverseOrder : ascendingOrder).map(child => child.childElement));
    }, [reverse, children, placement])

    return <div className={classes}>{childComponent}</div>
}

Timeline.defaultProps = {
    reverse: true,
    placement: 'up'
}

export default Timeline;